% mtg_good.m - create a *_good.mtg file .mtg file 
% 
% NOT "good_chs" (global!) as before (dist only)
%
% elm - 8/24/04
%     - 10/19/04 - rewritten to run outside of p_pods "i_config" loop
%       1st loop though each configs .gch file to determine # of good
%       channels in each mtg
%       2nd open full montage file
%       3rd write #s of good chans as "header" to _good.mtg
%       4th loop through configs and write good channel lables to _good.mtg

function mtg_good()

global hdr file_name logid n2 final_good_chs avg_PathName
% n_good mtg good_mtg lambda good_lambda

fprintf(logid,'Running mtg_good.m\n')

% k=strfind(file_name,'.');
% file_name=file_name(1:k(1));

% n_thresh=10; % add a GUI field for this !!!

% 1st; loop through configs, stashing # of good chans
%
for j_config=1:size(hdr.config,1)
    temp=final_good_chs{j_config};
    temp2=length(temp);
    n_good(j_config)=temp2;
end

% 2nd; read the full montage file (.mtg)
%
mtg_file = [hdr.data_path hdr.exp_name 'reg\' file_name '.mtg'];
fprintf(logid,'Loading full montage file: %s\n',mtg_file);
mtg = textread(mtg_file,'%s','delimiter','\n','whitespace','');
mtg = mtg(3:length(mtg));

% 3rd;  open the _good.mtg file and
% write the # of good channels in each config
%
out_file = [avg_PathName '\' file_name '_good.mtg'];
fprintf(logid,'Writing good montage file: %s\n',out_file);
out_fid = fopen(out_file,'w');
fprintf(out_fid,'NEW\r\n');
fprintf(out_fid,'%d ',n_good);  % number of good channels for each mtg.
fprintf(out_fid,'\r\n');

% 4th; loop through configs, writing good channel labels to _good.mtg
%
total_index = 1; % final_good_ch counter
for i_config=1:size(hdr.config,1)
%     cf=deblank(hdr.config(i_config,:));
%     fprintf(logid,'Loading %s...\n',[file_name cf '.gcq']);
    stop=sum(hdr.mchans(1:i_config));
    start=stop-hdr.mchans(i_config);
    good_mtg=cellstr(mtg(final_good_chs{i_config}+start));
    fprintf('Size of good_mtg is %d\n',size(good_mtg,1));
%     keyboard
    for i=1:n_good(i_config)
        fprintf(out_fid,'%d\t%s\r\n',total_index,char(good_mtg(i)));        
        total_index = total_index + 1;
%         pause(.1)
    end
end

fclose(out_fid);
